﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System;

namespace BlackJack.Infrastructure.Helpers
{
    public static class JSONHelper
    {
        public static string ToJSON<T>(this T obj)
            where T : class
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractJsonSerializer(typeof(T));

                serializer.WriteObject(stream, obj);

                byte[] json = stream.ToArray();

                stream.Close();

                return Encoding.UTF8.GetString(json, 0, json.Length);
            }
        }

        public static object FromJSON(this string json, Type type)
        {
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);

                var obj = serializer.ReadObject(stream);

                stream.Close();

                return obj;
            }
        }
    }

}
